package com.yfunc.common.event.handlers;

import java.lang.reflect.Method;
import java.util.Arrays;

import com.yfunc.common.event.Event;
import com.yfunc.common.event.EventHandler;

public abstract class AbstractEventHandler implements EventHandler {

	public abstract Class<?>[] supportedEvents();

	@Override
	public void handle(Event event) {
		try {
			Method method =  this.getClass().getMethod("when", event.getClass());
			method.invoke(this, event);
		} catch (Exception e) {
			throw new RuntimeException(this.getClass().getName() + " Not Implements Method: when(" + event.getClass() +")");
		}
		
	}

	@Override
	public boolean isSupported(Event event) {
		if( event == null){
			return false;
		}
		for (Class supportedEventClass : supportedEvents()) {
			if(supportedEventClass != null && supportedEventClass.equals(event.getClass())) {
				return true;
			}
		}
		return false;
	}
	
	
	
	@Override
	public boolean equals(Object obj) {
		if(obj != null && obj instanceof AbstractEventHandler ) {
			AbstractEventHandler absHandler = (AbstractEventHandler)obj;
			return Arrays.equals(this.supportedEvents(), absHandler.supportedEvents());
		}
		return false;
	}
	
	@Override
	public int hashCode() {
		int hash = 3377 * 11 ;
		for (Class supportedEventClass : supportedEvents()) {
			hash += supportedEventClass.hashCode();
		}
		return hash;
	}

}
